var gulp = require('gulp');
var merge = require('merge-stream');
var runSequence = require('run-sequence');
var rename = require("gulp-rename");
var del = require('del');
var vinylPaths = require('vinyl-paths');

var commonTask = require('./tasks/build.common.js');
var prodTask = require('./tasks/build.prod.js');
var cdnMD5 = require('./tasks/tools/cdnMD5');
var taskPath = require('./tasks/path');

var args = process.argv.slice(2);
var version = args[args.length - 1] === '--env' ? 'v1.0.1' : args[args.length - 1];

var fileMD5Map;
var contentMap;

gulp.task('default', function (callback) {
    runSequence(
        ['clean'],
        [
            'copy:res:other',
            'copy:res:libs',
            'copy:res:config',
            'copy:res:css',
            'copy:res:version',
            'mini:res:egret',
            'mini:resource'
        ],
        ['md5:cdn:file'],
        // ['rename:file:type2'],
        ['inject:index.html', 'inject:auth.html'],
        callback);
});

// 清除打包文件
gulp.task('clean', commonTask.clean);

// 复制项目下面的libs的公共类库js
gulp.task('copy:res:libs', function (callback) {
    return prodTask.copyResLibs(callback)
});

// 复制项目下面的libs的css文件
gulp.task('copy:res:css', function (callback) {
    return prodTask.copyResCss(callback)
});

// 复制项目下面的libs的wxConfig.js
gulp.task('copy:res:config', function (callback) {
    return prodTask.copyResConfig(callback)
});

// 复制其他不处理文件
gulp.task('copy:res:other', function (callback) {
    return commonTask.copyResOther(callback)
});

// 复制版本文件：main.min.js、index.html
gulp.task('copy:res:version', function (callback) {
    return commonTask.copyResVersion(version)
});

// 压缩egret引擎js
gulp.task('mini:res:egret', function ( callback ) {
    return commonTask.copyResEgretWithVer(version);
});

// release版本目录下复制resource资源
gulp.task('copy:res:version:resource', function (callback) {
    return commonTask.copyResWithVerAndDir(version, 'resource');
});

// release版本目录下压缩resource资源
gulp.task('mini:resource', ['copy:res:version:resource'], function ( callback ) {
    // 压缩json文件
    var taskJson = commonTask.minifyResourceJson('resource');
    return taskJson;

    // 压缩png/jpg资源
    var taskImage = commonTask.minifyResourceImg('resource');
    return merge(taskJson, taskImage);
});

// 读取cdn文件和本地文件做对比
gulp.task('md5:cdn:file', function (callback) {
    cdnMD5.run((fileMap) => {
        fileMD5Map = fileMap;
        callback();
    });
});

// 写入rulesCfg类型为2的文件
gulp.task('rename:file:type2', function (callback) {
    var tasks = [];
    var task1;
    var task2;
    for (var key in fileMD5Map) {
        if (fileMD5Map.hasOwnProperty(key)) {
            var item = fileMD5Map[key];
            console.log(item);
            if (item.type == 2) {
                var keyArr = key.split('/');
                var path = keyArr.slice(0, keyArr.length - 1).join('/');

                var fullname = keyArr[keyArr.length - 1];
                var name = fullname.replace(new RegExp(item.ext + '$'), '');
                var fileName = `${name}.${item.md5}${item.ext}`;

                var src = `${taskPath.DIR_BUILD}${key}`;
                var dist = `${taskPath.DIR_BUILD}${path}`;
                task1 = gulp.src(src)
                    .pipe(rename(fileName))
                    .pipe(gulp.dest(dist));

                task2 = gulp.src(src)
                    .pipe(gulp.dest(dist))
                    .pipe(vinylPaths(del));

                tasks.push(task1);
                tasks.push(task2);
            }
        }
    }

    if (tasks.length)
        return merge(tasks);
    else {
        callback();
    }
});

// inject插入html
gulp.task('inject:index.html', function (callback) {
    runSequence(
        ['inject:index.html:vendons'],
        ['inject:index.html:css'],
        ['inject:index.html:egret'],
        ['inject:index.html:main'],
        callback
    );
});

// inject插入index.html的类库vendons js
gulp.task('inject:index.html:vendons', function (callback) {
    var key = `/libs/${taskPath.RES_LIBS.prod}`;
    var md5Url = fileMD5Map[key].md5Url;
    return commonTask.injectHtmlWithTag(
        'index',
        md5Url,
        '<!--other_libs_files_start-->',
        '<!--other_libs_files_end-->'
    );
});

// inject插入index.html的css
gulp.task('inject:index.html:css', function (callback) {
    var key = `/libs/${taskPath.RES_CSS.prod}`;
    var md5Url = fileMD5Map[key].md5Url;
    return commonTask.injectHtmlWithTag(
        'index',
        md5Url,
        '<!--other_css_files_start-->',
        '<!--other_css_files_end-->',
        {
            style: 2
        }
    );
});

// inject插入index.html的egret js
gulp.task('inject:index.html:egret', function (callback) {
    var key = `/libs/${taskPath.RES_EGRET.common}`;
    var md5Url = fileMD5Map[key].md5Url;
    return commonTask.injectHtmlWithTag(
        'index',
        md5Url,
        '<!--modules_files_start-->',
        '<!--modules_files_end-->',
        {
            'egret': 'lib'
        }
    );
});

// inject插入index.html的main.min.js
gulp.task('inject:index.html:main', function (callback) {
    var key = '/libs/main.min.js';
    var md5Url = fileMD5Map[key].md5Url;
    return commonTask.injectHtmlWithTag(
        'index',
        md5Url,
        '<!--game_files_start-->',
        '<!--game_files_end-->'
    );
});

// inject插入getAuth.html、weixinAuth.html
gulp.task('inject:auth.html', function (callback) {
    runSequence(
        [
            'inject:getAuth.html:config',
            'inject:weixinAuth.html:config'
        ],
        callback
    );
});

// inject插入getAuth.html的类库config js
gulp.task('inject:getAuth.html:config', function (callback) {
    var key = `/libs/${taskPath.RES_CONFIG.prod}`;
    var md5Url = fileMD5Map[key].md5Url;
    return commonTask.injectHtmlWithTag(
        'getAuth',
        md5Url,
        '<!--other_libs_files_start-->',
        '<!--other_libs_files_end-->'
    );
});

// inject插入weixinAuth.html的类库config js
gulp.task('inject:weixinAuth.html:config', function (callback) {
    var key = `/libs/${taskPath.RES_CONFIG.prod}`;
    var md5Url = fileMD5Map[key].md5Url;
    return commonTask.injectHtmlWithTag(
        'weixinAuth',
        md5Url,
        '<!--other_libs_files_start-->',
        '<!--other_libs_files_end-->'
    );
});

// 开启服务器
gulp.task('open:server', function () {
    commonTask.openServer();
});